package net.mysoft.budgetsoft.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import net.mysoft.budgetsoft.system.dao.GongNengJSDao;
import net.mysoft.budgetsoft.system.domain.TGongNengJS;
import net.mysoft.budgetsoft.system.pagemodel.GongNengJS;
import net.mysoft.budgetsoft.system.service.GongNengJSService;
import net.mysoft.framework.model.DataGrid;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * 
 * @author dagongPGP v1.0
 * @link <a href=http://www.dagongsoft.net>北京大公信软科技有限公司</a>
 * 
 * @version $Revision: 1.00 $Date: 2013-12-27 14:28:41
 */
@Service("gongNengJSService")
public class GongNengJSServiceImpl implements GongNengJSService {
	@Resource
	private GongNengJSDao gongNengJSDao;

	public GongNengJSDao getGongNengJSDao() {
		return this.gongNengJSDao;
	}

	public void setGongNengJSDao(GongNengJSDao gongNengJSDao) {
		this.gongNengJSDao = gongNengJSDao;
	}

	@Override
	public void add(GongNengJS gongNengJS) {
		TGongNengJS t = new TGongNengJS();
		BeanUtils.copyProperties(gongNengJS, t);
		t.setBianHao(UUID.randomUUID().toString());
		gongNengJSDao.save(t);
	}

	@Override
	public void edit(GongNengJS gongNengJS) {
		TGongNengJS t = new TGongNengJS();
		BeanUtils.copyProperties(gongNengJS, t);
		gongNengJSDao.update(t);
	}

	@Override
	public void delete(GongNengJS gongNengJS) {
		for (String id : gongNengJS.getIds().split(",")) {
			Object t = gongNengJSDao.get(TGongNengJS.class, id);
			if (t != null) {
				gongNengJSDao.delete(t);
			}
		}
	}

	@Override
	public DataGrid datagrid(GongNengJS gongNengJS) {
		DataGrid dg = new DataGrid();
		String hql = "from TGongNengJS t ";
		List params = new ArrayList();
		hql = addWhere(gongNengJS, hql, params);
		hql = addOrder(gongNengJS, hql);
		String totalHql = "select count(*) " + hql;
		List<TGongNengJS> toList = gongNengJSDao.find(hql, params, gongNengJS.getPage(), gongNengJS.getRows());
		List<GongNengJS> oList = new ArrayList<GongNengJS>();
		oList = changeModel(toList);
		dg.setTotal(gongNengJSDao.count(totalHql, params));
		dg.setRows(oList);
		return dg;
	}

	private String addWhere(GongNengJS gongNengJS, String hql, List<Object> params) {
		return hql;
	}

	private String addOrder(GongNengJS gongNengJS, String hql) {
		if (gongNengJS.getSort() != null) {
			hql += " order by " + gongNengJS.getSort() + " " + gongNengJS.getOrder();
		}
		return hql;
	}

	public List<GongNengJS> changeModel(List<TGongNengJS> tGongNengJS) {
		List<GongNengJS> list = new ArrayList<GongNengJS>();
		for (TGongNengJS to : tGongNengJS) {
			GongNengJS o = new GongNengJS();
			BeanUtils.copyProperties(to, o);
			list.add(o);
		}
		return list;
	}
}
